var keyPrefix = 'UNIFIEDChallengesCheckPlayTool.';

GM_log = function(message) {
	console.info(message);
};

GM_addStyle = function(css) {
        var head = document.getElementsByTagName('head')[0], style = document.createElement('style');
        if (!head) {return; }
        style.type = 'text/css';
        try {style.innerHTML = css;} catch(x) {style.innerText = css;}
        head.appendChild(style);
};

GM_getValue = function(key, defValue) {
	var retval = window.localStorage.getItem(keyPrefix + key);
	if (!$chk(retval)) {
		return defValue;
	}
	return retval;
};

GM_setValue = function(key, value) {
	try {
		window.localStorage.setItem(keyPrefix + key, value);
	} catch(e) {
		GM_log("error setting value: " + e);
	}
};

GM_deleteValue = function(key) {
	try {
		window.localStorage.removeItem(keyPrefix + key);
	} catch(e) {
		GM_log("error removing value: " + e);
	}
};

GM_listKeys = function(regexp, callback) {
	var list = [];
	var reKey = new RegExp("^" + keyPrefix); // first, make sure we only use our own keys
	for (var i = 0, il = window.localStorage.length; i < il; i++) {
		// only use the script's own keys
		var key = window.localStorage.key(i);
		try {
			if (key && key.match(reKey)) {
				var unprefixedKey = key.replace(keyPrefix, '');
				if (regexp) {
					if (unprefixedKey.match(regexp)) {
						if (callback) {
							callback(unprefixedKey);
						} else {
							list.push(unprefixedKey);
						}
					}
				} else {
					if (callback) {
						callback(unprefixedKey);
					} else {
						list.push(unprefixedKey);
					}
				}
			}
		} catch(e) {
			GM_log("error in listKeys: " + e);
		}
	}
	return list;
};

GM_getObject = function(key) {
	var value = GM_getValue(key);
	if ($chk(value)) {
		try {
			return JSON.parse(value);

		} catch(e) {
			var error = "error parsing (" + e + ") object '" + key + "': " + value;
			GM_log(error);
			return null;
		}
	}
	return null;
};

GM_storeObject = function(key, value) {
	GM_setValue(key, JSON.stringify(value));
};

var getJSVariable = function(regex) {
	// Thanks to Vispillo for this compact code
	var retval = null;
	$$('script').each(function(script) {
		if (retval != null) {
			return;
		}
		var html = script.innerHTML;
		try {
			retval = html.match(regex)[1];
		} catch(e) {
		}
	});
	return retval;
};

var GM_getSessionKey = function () {
	return getJSVariable(/\"api_key\"[ :]+\"([^\"]+)\"/);
};

var convertEscapedUnicode = function (str) {
	if (str.match('\\u[0-9a-f]{4}')) {
		var match = str.match(/(.*)\\u([0-9a-f]{4})(.*)/);
		if ($chk(match)) { // with both ends
			return convertEscapedUnicode(match[1]) + String.fromCharCode(parseInt(match[2],16)) + convertEscapedUnicode(match[3]);
		}
		match = str.match(/(.*)\\u([0-9a-f]{4})/);
		if ($chk(match)) { // only front end
			return convertEscapedUnicode(match[1]) + String.fromCharCode(parseInt(match[2],16));
		}
		match = str.match(/\\u([0-9a-f]{4})(.*)/);
		if ($chk(match)) { // only back end
			return String.fromCharCode(parseInt(match[1],16)) + convertEscapedUnicode(match[2]);
		}
		match = str.match(/\\u([0-9a-f]{4})/);
		if ($chk(match)) { // sanity check
			return String.fromCharCode(parseInt(match[1],16));
		}
		return str;
	} else {
		return str;
	}
};

GM_getLoggedInUser = function () {
	var username = getJSVariable(/[\"\']user[\"\'][ :]+{[^}]*[\"\']name[\"\'][ :]+[\'\"]([^\'\"]+)[\'\"]/);
	if (!$chk(username)) {
		GM_log("DEBUG: user name not found in JSON data");
		username = getJSVariable(/global_name\s*=\s*\'([^\']+)\'/);
	}
	if (!$chk(username)) {
		GM_log("DEBUG: user name not found in global_variables");
	    try {
		username = $('TopBar').getElement('table.Header').getElement('td.Status').getElement('a.Pale').get('text'); // use 'text', not 'html' (replaces &amp; with & ..)
	    } catch (e) {
		try {
			username = $('TopBar').getElement('table.Header').getElement('td.Status').getElement('a.ywa-track').get('text');
		} catch (f) {
			GM_log("unable to retrieve user (" + f + ")");
		}
	    }
	}
	return convertEscapedUnicode(username);
};

GM_getGlobalNsid = function () {
	var usernsid = getJSVariable(/[\"\']user[\"\'][ :]+{[^}]*[\"\']nsid[\"\'][ :]+[\'\"]([^\'\"]+)[\'\"]/);
	if (!$chk(usernsid)) {
		GM_log("WARNING: nsid not found in JSON data");
		usernsid = getJSVariable(/global_nsid\s*=\s*\'([^\']+)\'/);
	}
	return usernsid;
};

GM_getPublicKey = function() {
	return GM_getSessionKey();
        // the following api_key is reserved for this application
        // if you need an api_key for your own application, please request one at 
        // http://www.flickr.com/services/apps/create/apply/
        // if you request a Non-Commercial key, you'll get it instantly
        return 'a78ba83c374022595dc9073986735dcb'; // the app's own key
};

GM_getPrivateKey = function() {
	return getJSVariable(/[\'\"]api_key[\'\"][ :]+[\'\"]([^\'\"]+)[\'\"]/);
};

GM_getAuthHash = function () {
	var authhash = getJSVariable(/[\"\']auth_hash[\"\'][ :]+[\"\']([^\"\']+)[\"\']/);
	if (!$chk(authhash)) {
		//GM_log("WARNING: auth hash not found in JSON data");
		authhash = getJSVariable(/global_auth_hash[ =]+\'([^\']+)\'/);
	}
	return authhash;
};

GM_getAuthToken = function () {
	var authtoken = getJSVariable(/[\"\']auth_token[\"\'][ :]+[\"\']([^\"\']*)[\"\']/);
	if (!$chk(authtoken)) {
		//GM_log("WARNING: auth token not found in JSON data");
		authtoken = getJSVariable(/global_auth_token[ =]+\'([^\']*)\'/);
	}
	return authtoken;
};

GM_getGroupId = function () {
	var groupID = getJSVariable(/[\"\']group[\"\'][: ]+{[^}]*[\"\']nsid[\"\'][: ]+[\"\'](\d+@\w\d{2})[\"\']/);
	if (!$chk(groupID)) {
    		groupID = getJSVariable(/\"search_scope\"[ :]+\"([^\"]+)\"/);
	}
	return groupID;
};
